﻿using System.ComponentModel.DataAnnotations;
using System.ServiceModel;

namespace IssueVision.EntityModel
{
    /// <summary>
    /// Issue class validation logic
    /// </summary>
    [CustomValidation(typeof(IssueRules), "CheckStatusActive")]
    [CustomValidation(typeof(IssueRules), "CheckStatusOpen")]
    //[CustomValidation(typeof(IssueRules), "CheckStatusResolved")]
    public partial class Issue
    {
        /// <summary>
        /// Partial method to add all validation actions
        /// defined for this class
        /// </summary>
        partial void InitializeValidationSettings()
        {
#if SILVERLIGHT
            // there are top-level validation actions defined for this class
            // so, we need to enable this property.
            ValidateEntityOnPropertyChanged = true;
#endif
            AddPropertyValidationAction(string.Empty, ValidateStatusResolved);
        }

        #region "Private Validation Methods"

        /// <summary>
        /// Validation Action:
        /// When status is Resolved, the ResolutionID cannot be null or zero,
        /// and when the status is not Resolved, the ResolutionID should be
        /// either null or zero.
        /// </summary>
        /// <param name="value"></param>
        private void ValidateStatusResolved(object value)
        {
            Issue issue = value as Issue;

            if (issue != null)
            {
                if (issue.StatusID == IssueVisionServiceConstant.ResolvedStatusID &&
                    (issue.ResolutionID == null || issue.ResolutionID == 0))
                {
#if SILVERLIGHT
                ValidationResult result = new ValidationResult("Resolution is required when the status is Resolved.", new[] { "StatusID", "ResolutionID" });
                AddError("StatusID", result);
                AddError("ResolutionID", result);
#else
                    FaultReason faultReason = new FaultReason("Resolution is required when the status is Resolved.");
                    throw new FaultException(faultReason);
#endif
                }

                if (issue.StatusID != IssueVisionServiceConstant.ResolvedStatusID &&
                    issue.ResolutionID != null && issue.ResolutionID != 0)
                {
#if SILVERLIGHT
                // client-side logic
                ValidationResult result = new ValidationResult("Resolution is not needed when the status is not Resolved.", new[] { "StatusID", "ResolutionID" });
                AddError("StatusID", result);
                AddError("ResolutionID", result);
#else
                    // server-side logic
                    FaultReason faultReason = new FaultReason("Resolution is not needed when the status is not Resolved.");
                    throw new FaultException(faultReason);
#endif
                }
            }
        }

        #endregion "Private Validation Methods"
    }
}
